<template>
  <div class="active">
    <!-- 弹出表单 -->
    <el-dialog
      destroy-on-close
      :title="state.dialogs.name"
      top="5vh"
      lock-scroll
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      v-model="state.dialogs.insert"
    >
      <el-form
        label-position="top"
        :model="state.insertForm"
        :rules="state.rules"
        ref="insertFormRef"
        size="small"
        label-width="1rem"
      >
        <el-row :gutter="50">
          <el-col :span="6">
            <el-form-item label="标题" prop="title">
              <el-input v-model.trim="state.insertForm.title" placeholder="请输入文章标题" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="作者" prop="author">
              <el-input v-model.trim="state.insertForm.author" placeholder="请输入文章作者" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="分类" prop="category">
              <el-select placeholder="请选择文章分类" v-model="state.insertForm.category">
                <el-option
                  v-for="(cate, index) in state.categorys"
                  :value="cate.label"
                  :label="cate.label"
                  :key="index"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="6">
          <el-form-item label="状态" prop="status">
            <el-select v-model="state.insertForm.status">
              <el-option
                v-for="(cate, index) in state.status"
                :value="cate"
                :label="cate.label"
                :key="index"
              ></el-option>
            </el-select>
          </el-form-item>
          </el-col>-->
          <el-col :span="24">
            <el-form-item label="封面图片" prop="cover">
              <Cover @srcChange="srcChange" :src="state.insertForm.cover" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="描述" prop="desc">
              <el-input
                :maxlength="300"
                type="textarea"
                placeholder="请输入文章描述"
                v-model.trim="state.insertForm.desc"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="内容" prop="html"> </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="state.dialogs.insert = false">取消</el-button>
          <el-button v-if="state.dialogs.name == '修改文章'" type="primary" @click="submitUpdate"
            >修改</el-button
          >
          <el-button v-else type="primary" @click="submitInsert">确定</el-button> </span
        >s
      </template>
    </el-dialog>
    <el-dialog title="查看文章" v-model="state.dialogs.view" width="40%">
      <div class="view">
        <h1>查看文章</h1>
      </div>
    </el-dialog>

    <!-- 表格 -->
    <section class="table-form">
      <div class="table-toolbar">
        <div class="btns">
          <el-button icon="el-icon-plus" size="mini" type="primary" @click="showInsertDialog" plain
            >新增</el-button
          >
          <!-- <el-button icon="el-icon-edit" size="mini" type="success" plain>修改</el-button>
          <el-button icon="el-icon-delete" size="mini" type="danger" plain>删除</el-button>
          <el-button icon="el-icon-search" size="mini" type="warning" plain>导出</el-button>
          <el-button icon="el-icon-refresh" size="mini" type="primary" plain>刷新</el-button>-->
        </div>
        <div class="right">
          <el-tooltip content="隐藏搜索栏" placement="top">
            <el-button circle size="mini" icon="el-icon-search" @click="showQueryForm"></el-button>
          </el-tooltip>
          <el-tooltip content="刷新数据" placement="top">
            <el-button @click="refech" circle size="mini" icon="el-icon-refresh"></el-button>
          </el-tooltip>
        </div>
      </div>
      <el-table
        stripe
        highlight-current-row
        style="width: 100%"
        fit
        :indent="60"
        :data="state.tableData"
      >
        <el-table-column type="selection" align="center"></el-table-column>
        <el-table-column
          :show-overflow-tooltip="true"
          align="center"
          v-for="item in state.taballFields"
          :class="item.prop"
          :key="item.prop"
          v-bind="item"
        >
          <template v-if="item.prop == 'cover'" #default="scope">
            <el-image :src="scope.row.cover" fit="fill" :lazy="true"></el-image>
          </template>
          <template v-if="item.prop == 'category'" #default="scope">
            <el-tag>{{ scope.row.category }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作">
          <template #default="{ row }">
            <div class="btns">
              <el-button
                circle
                size="mini"
                icon="el-icon-view"
                @click="() => showViewDialog()"
              ></el-button>
              <el-button
                circle
                size="mini"
                icon="el-icon-edit"
                @click="() => getArtDetailSync(row._id)"
              ></el-button>
              <el-popconfirm title="你确定要删除此文章么？" @confirm="() => deleteArtSync(row._id)">
                <template #reference>
                  <el-button circle size="mini" type="danger" icon="el-icon-delete"></el-button>
                </template>
              </el-popconfirm>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        class="pagination"
        :current-page="1"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="20"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        layout="total, sizes, prev, pager, next, jumper"
        :total="1"
      ></el-pagination>
    </section>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { format } from '../utils/day'

// Http
import { getArtList, getArtDetail, insertArt, updateArt, deleteArt } from '../api/art'

// Component
import Cover from '../components/cover.vue'
import { getCategorys } from '../api/category'

onMounted(() => {
  refech()
  getCateList()
})

const state = reactive<any>({
  categorys: [], // 分类
  status: [], // 状态
  insertForm: {
    title: '',
    author: '',
    category: '',
    desc: '',
    html: '',
    cover: '',
  }, //添加
  rules: {
    title: {
      required: true,
      message: '请填写文章标题',
      trigger: ['blur', 'change'],
    },
    author: {
      required: true,
      message: '请填写作者',
      trigger: ['blur', 'change'],
    },
    category: {
      required: true,
      message: '请选择文章分类',
      trigger: ['blur', 'change'],
    },
    cover: {
      required: true,
      message: '请选择一个文章封面',
    },
    desc: [
      {
        required: true,
        message: '请填写文章描述',
        trigger: ['blur', 'change'],
      },
      {
        min: 5,
        message: '文章描述不少于5个字符',
        trigger: ['blur', 'change'],
      },
    ],
    html: {
      required: true,
      message: '请填写文章内容',
    },
  },
  tableData: [],
  taballFields: [
    {
      label: '标题',
      prop: 'title',
      width: '150px',
    },
    {
      label: '描述',
      prop: 'desc',
      width: '200px',
    },
    {
      label: '封面',
      prop: 'cover',
      width: '200px',
    },
    {
      label: '查看',
      prop: 'watch',
      width: '80px',
    },
    {
      label: '点赞',
      prop: 'like',
      width: '80px',
    },
    {
      label: '分类',
      prop: 'category',
      width: '80px',
    },
    {
      label: '状态',
      prop: 'status.label',
      width: '80px',
    },
    {
      label: '更新时间',
      prop: 'updatedAt',
      width: '150px',
    },
    {
      label: '创建时间',
      prop: 'createdAt',
      width: '150px',
    },
  ],
  dialogs: {
    name: '添加文章',
    insert: false,
    view: false,
  },
})

// 刷新表格数据
const refech = async () => {
  const { arts } = await getArtList({})
  arts.forEach((art: Article) => {
    art.createdAt = format(art.createdAt as any, 'YYYY-MM-DD')
    art.updatedAt = format(art.updatedAt as any, 'YYYY-MM-DD')
  })
  state.tableData = [...arts]
}

// <<------------ state ---------->>

// 文件列表
let art_id = ref('')

// 获取分类列表
const getCateList = async () => {
  const categorys = await getCategorys()
  state.categorys = categorys
}

// <<------------ Dom ---------->>
const queryform = ref()
const insertFormRef: any = ref()

// <<------------ methods ---------->>
const showQueryForm = () => {}

const showViewDialog = () => {
  state.dialogs.view = true
}
const showInsertDialog = () => {
  state.dialogs.insert = true
}
const closeDialog = (name: string) => {
  state.dialogs[name] = false
}
const handleSizeChange = () => {}
const handleCurrentChange = () => {}

const srcChange = (src: string) => {
  state.insertForm.cover = src
}

const submitInsert = () => {
  insertFormRef.value.validate((valid: boolean) => {
    if (valid) {
      const artInfo = { ...state.insertForm }
      insertArt(artInfo).then(res => {
        if (res.code) {
          refech()
          closeDialog('insert')
        }
      })
    }
  })
}
const submitUpdate = () => {
  insertFormRef.value.validate((valid: boolean) => {
    if (valid) {
      if (!art_id.value) {
        console.log('目标不存在')
        return
      }
      updateArt(art_id.value, state.insertForm).then(res => {
        if (res.code) {
          refech()
          closeDialog('insert')
        }
      })
    }
  })
}

const getArtDetailSync = async (_id: string) => {
  art_id.value = _id
  const art = ((await getArtDetail(_id)) as any).art as Article
  if (art) {
    state.insertForm = { ...art }
  }
  showInsertDialog()
  state.dialogs.name = '修改文章'
}

const deleteArtSync = async (_id: string) => {
  const ret: any = await deleteArt(_id)
  if (ret.code) {
    ElMessage.success(ret.message)
    refech()
  } else {
    ElMessage.success(ret.message)
  }
}

const getHtml = (html: string) => {
  state.insertForm.html = html
}
</script>

<style lang="scss" scoped>
.search-bar {
  background-color: #fff;
  box-sizing: border-box;
  width: 100%;
  padding: 10px;
  .el-form {
    .inputs {
      display: flex;
      align-items: center;
      flex-wrap: wrap;
      .input {
        flex-basis: 240px;
        justify-content: flex-start;
        margin: 10px;
      }
      .btns {
        justify-content: flex-start;
      }
      .el-form-item {
        margin-bottom: 0;
      }
    }
  }
}

.table-form {
  margin-top: 20px;
  .table-toolbar {
    @include flex-center;
    padding: 10px;
    background-color: #fff;
    justify-content: flex-start;
    .right {
      margin-left: auto;
    }
  }
  .btns {
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
    .el-button {
      margin: 0px;
      margin: 5px;
    }
  }
  .pagination {
    margin-top: 20px;
    text-align: right;
  }
}

:deep(.el-overlay) {
  &::-webkit-scrollbar {
    display: none;
  }
}

:deep(.el-dialog) {
  width: 80vw !important;
  .el-form {
    height: 500px;
    overflow-y: scroll;
    &::-webkit-scrollbar {
      display: none;
    }
    // .el-form-item {
    //   .el-input {
    //   }
    // }
  }
}
.el-dialog {
  .article {
    margin: 20px;
    line-height: 1.6;
  }
}
// 滚动条的宽度
:deep(.el-table__body-wrapper::-webkit-scrollbar) {
  width: 5px; // 横向滚动条
  height: 10px; // 纵向滚动条 必写
}

// 滚动条的滑块
:deep(.el-table__body-wrapper::-webkit-scrollbar-thumb) {
  background-color: #ddd;
  border-radius: 30px;
}
</style>
